from eventServer import eventServer

class TimeServer:
    def __init__(self):
        eventServer.addProvider("time",self.provideTime)
        
        self.nextTimes = {}
        self.frameTimes = {}
    
    def provideTime(self, cmd):
        eventServer.subscribe("update",self.update)
        fps = int(cmd)
        if fps not in self.nextTimes:
            self.nextTimes[fps] = None
            self.frameTimes[fps] = 1.0 / float(fps)
    
    def update(self, args):
        time = args['time']
        
        for fps, nextTime in self.nextTimes.items():
            if not nextTime or time > nextTime:
                frameTime = self.frameTimes[fps]
                nextTime = nextTime or time
                eventServer.localPublish("time_%d" % fps, time = time, dtime = time - nextTime + frameTime)
                self.nextTimes[fps] = nextTime + frameTime
                
    def subscribe(self, fps, f):
        eventServer.subscribe("time_%d" % int(fps), f)

timeServer = TimeServer()
